/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "logger.h"

#include <stdarg.h>
#include <stddef.h>

#include "securec.h"

#define MAX_BUFF_SIZE 384

#define VA_ARGS_PROCESS(logger, fmt, buffer)                                            \
    do {                                                                                \
        va_list args;                                                                   \
        va_start(args, (fmt));                                                          \
        int ret = vsnprintf_s((buffer), MAX_BUFF_SIZE, MAX_BUFF_SIZE - 1, (fmt), args); \
        va_end(args);                                                                   \
        if (ret > 0) {                                                                  \
            logger(buffer);                                                             \
        }                                                                               \
    } while (0)

static Logger g_logger = {0};

void SetApduLogger(const Logger *logger)
{
    if (logger == NULL) {
        return;
    }
    g_logger.debug = logger->debug;
    g_logger.error = logger->error;
    g_logger.info = logger->info;
}

__attribute__((weak)) void LogDebug(const char *fmt, ...)
{
    if (g_logger.debug == NULL) {
        return;
    }
    char buff[MAX_BUFF_SIZE + 1] = {0};
    VA_ARGS_PROCESS(g_logger.debug, fmt, buff);
}

__attribute__((weak)) void LogInfo(const char *fmt, ...)
{
    if (g_logger.info == NULL) {
        return;
    }
    char buff[MAX_BUFF_SIZE + 1] = {0};
    VA_ARGS_PROCESS(g_logger.info, fmt, buff);
}

__attribute__((weak)) void LogError(const char *fmt, ...)
{
    if (g_logger.error == NULL) {
        return;
    }
    char buff[MAX_BUFF_SIZE + 1] = {0};
    VA_ARGS_PROCESS(g_logger.error, fmt, buff);
}
